/**
 * Created by xuchaosheng on 16/5/22.
 */
services.factory("tools", ["$http", "$rootScope", "$timeout","$q","Session",function ($http, $rootScope, $timeout,$q,Session) {
    return {
        $post:function(param){

            if (!param instanceof Object || !param.url) {
                return;
            }  
       
            var defer = $q.defer();
            //{url:xx:data:{xx:xx}}          
            $http({
                method: 'post',
                url: param.url,
                data: param.data,
                headers:{'Content-Type': 'application/x-www-form-urlencoded'},
                transformRequest: function(obj) {    
                    var str = [];    
                    for (var p in obj) {    
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));    
                    }    
                    return str.join("&");    
                }   
            }).then(function(resp){
                console.log(resp);
                console.log('88888')
                var resp = resp.data;
               
                if (resp.value == "session expired") {
                    Session.destroy();
                    window.location.href = '/index';
                    return;
                }
                if(resp.success){
                    defer.resolve(resp);
                }else{
                    defer.reject(resp);
                }
            },function(err){
                var resp = resp.data;
               
                defer.reject(err);
            });

            return defer.promise;
        },
        $get:function(param){

            if (!param instanceof Object || !param.url) {
                return;
            }
            var self = this;
            var defer = $q.defer();
            $http({
                method: 'GET',
                url: param.url,
                params: param.data || {},
                headers: {
                    'Accept': 'application/json, text/javascript, */*'
                }
            }).then(function (resp) {
                var resp = resp.data;
                console.log(resp);
                console.log('88888');
                if (resp.value == "session expired") {
                    Session.destroy();
                    window.location.href = '/index';
                    return;
                }
                if(resp.success){
                    defer.resolve(resp);
                }else{
                    defer.reject(resp);
                }
            },function (err) {
                defer.reject(err);
            });

            return defer.promise;
        },
        /*
         * 清除字符串两端的空格
         * */
        trim: function (str) {
            if (!str instanceof String)
                return str;
            var res = str.replace(/^\s+|\s+$/gi, "");
            return res;
        },
        /*
         * alert指令的简便调用模式
         * */
        alert: function (title, content) {
            $rootScope.$broadcast('alert', title, content);
            return false;
        },
        /*
         * confirm指令的简便调用模式
         * */
        confirm: function (config) {
            if (!config) {
                $rootScope.$broadcast('CONFIRM_OFF_EV');
                return;
            }
            $rootScope.$broadcast('CONFIRM_EV', config);
        },
        /*
         * info指令的简便调用模式
         * */
        msg: function (content) {
            $rootScope.$broadcast('MESSAGE_EV', content);
        },
        /*
         * 检查一个对象是否为空
         * */
        isEmpty: function (obj) {
            for (var i in obj) {
                return false;
            }
            return true;
        },
        /*
         * 用于跨页面保存数据
         * */
        data: {
            data: {
                itemlist: {
                    checkboxlist: {},
                    chartlist: {},
                    radiolist: {},
                    betweenlist: {},
                    selectlist: {},
                    datelist: {},
                    sheetlist: {},
                    notelist: {},
                    syncdatalist: {}
                }
            },
            setItem: function (key, value) {
                this.data[key] = value;
            },
            getItem: function (key) {
                return this.data[key];
            },
            delItem: function (key) {
                delete this.data[key];
            }
        },
        identifier: function () {
            var name = "";
            var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            for (var i = 0; i < 20; i++) {
                name += chars[Math.floor(Math.random() * 25)];
            }
            return name;
        },
        makeConditionId: function () {
            var id = "";
            var chars = '0123456789';
            for (var i = 0; i < 20; i++) {
                id += chars[Math.ceil(Math.random() * 9)];
            }
            return id;
        },
        tmpId: function () {
            var id = "";
            var chars = '0123456789';
            for (var i = 0; i < 20; i++) {
                id += chars[Math.ceil(Math.random() * 9)];
            }
            return Number(id);
        },
        fieldId: function () {
            return Math.floor(Math.random() * Math.random() * 10000000000);
        },
        isPreviewing: function () {
            return window.location.hash.indexOf("system") != -1;
        },
        isEditing: function () {
            return window.location.hash.indexOf("editor") != -1;
        },
        storage: {
            //var localStorage = window.localStorage;
            setItem: function (key, value) {
                window.localStorage.setItem(key, value);
            },
            getItem: function (key) {
                return window.localStorage.getItem(key);
            },
            removeItem: function (key) {
                window.localStorage.removeItem(key)
            }
        },
        gridwidth: function () {
            return Math.floor((window.screen.width * 0.95) / 80);
        },
        dragcontentwidth: function () {
            return (Math.floor((window.screen.width * 0.95) / 80)) * 80
        },
        screenCapture: function () {
            html2canvas(document.body).then(function (canvas) {
                $('.imgsrc').val(canvas.toDataURL())
            });
        },
        jsonToQueryStr: function (json) {
            var result = [];
            for (var i in json) {
                result.push(i + '=' + json[i]);
            }
            return result.join('&');
        },
        img2base64: function (src) {
            var c = document.createElement("canvas");
            c.width = 250;
            c.height = 250;
            var cxt = c.getContext("2d");
            var img = new Image();
            img.src = src;
            cxt.drawImage(img, 0, 0);
            var dd = c.toDataURL();
            console.log(dd)
        },
        userConfig: null,
        updateUserConfig: function (cb) {
            var self = this;
            if (!self.userConfig) {
                return;
            }

            var json_ = JSON.stringify(self.userConfig).replace(/:null/gi, ':""');
            this.get({
                url: '/Ibm-Client/updateUserConfig.htm',
                data: {
                    configInfo: json_
                },
                succ: function (resp) {
                    if (resp.success) {
                        cb && cb();
                    }
                }
            });
        },
        getUserConfig: function () {
            return this.userConfig;
        },
        initUserConfig: function (value) {
            this.userConfig = value.userConfig || {};
            this.userInfo = value;
        },
        refresh: function () {
            $timeout(function () {
            }, 0);
        },
        mobileEnv: function () {
            return window.location.href.indexOf('mobileMain') != -1;
        },
        isJiaguwen: function () {
            return window.location.host == 'app315.trenddata.cn';
        },
        isQushu: function () {
            return window.location.host == 'bi.trenddata.cn' || window.location.host == '127.0.0.1:8080';
        }
    }
}]);
services.service('Session', ['$cookies',function ($cookies) {

    if($cookies.getObject('session')){
        this.UserInfo = $cookies.getObject('session');
    }

    this.create = function (UserInfo) {
        this.UserInfo = UserInfo;
        var now = new Date();
        // this will set the expiration to 1 day
        now.setDate(now.getDate() + 1);
        $cookies.putObject('session',UserInfo,{'expires':now});
    };
    this.destroy = function () {
        this.UserInfo = null;
        $cookies.remove('session');
    };

    return this;
}]);

services.factory('SweetAlert', ['$rootScope', function ( $rootScope ) {

  //live-demos http://oitozero.github.io/ngSweetAlert/#/home
    /*

    demos
    SweetAlert.swal("Good job!", "You clicked the button!", "success");

        SweetAlert.swal({
           title: "Are you sure?",
           text: "Your will not be able to recover this imaginary file!",
           type: "warning",
           showCancelButton: true,
           confirmButtonColor: "#DD6B55",confirmButtonText: "Yes, delete it!",
           cancelButtonText: "No, cancel plx!",
           closeOnConfirm: false,
           closeOnCancel: false }, 
        function(isConfirm){ 
           if (isConfirm) {
              SweetAlert.swal("Deleted!", "Your imaginary file has been deleted.", "success");
           } else {
              SweetAlert.swal("Cancelled", "Your imaginary file is safe :)", "error");
           }
        });

    SweetAlert.swal({
       title: "Are you sure?",
       text: "Your will not be able to recover this imaginary file!",
       type: "warning",
       showCancelButton: true,
       confirmButtonColor: "#DD6B55",
       confirmButtonText: "Yes, delete it!",
       closeOnConfirm: false}, 
    function(){ 
       SweetAlert.swal("Booyah!");
    });
    SweetAlert.swal({
       title: "Sweet!",
       text: "Here's a custom image.",
       imageUrl: "http:://oitozero.com/avatar/avatar.jpg" });


    */

  var swal = window.swal;

  //public methods
  var self = {
    //arg3 warning error success info
    swal: function ( arg1, arg2, arg3 ) {
      $rootScope.$evalAsync(function(){
        if( typeof(arg2) === 'function' ) {
          swal( arg1, function(isConfirm){
            $rootScope.$evalAsync( function(){
              arg2(isConfirm);
            });
          }, arg3 );
        } else {
          swal( arg1, arg2, arg3 );
        }
      });
    },
    success: function(title, message) {
      $rootScope.$evalAsync(function(){
        swal( title, message, 'success' );
      });
    },
    error: function(title, message) {
      $rootScope.$evalAsync(function(){
        swal( title, message, 'error' );
      });
    },
    warning: function(title, message) {
      $rootScope.$evalAsync(function(){
        swal( title, message, 'warning' );
      });
    },
    info: function(title, message) {  
      $rootScope.$evalAsync(function(){
        swal( title, message, 'info' );
      });
    }
  };
  
  return self;
}]);

services.factory('NoticeServ',['$rootScope',function($rootScope){
    return{
        //订阅
        $on:function(scope,eventName,callback){
            if(!scope.Event_OFF){
                scope.Event_OFF = [];
            }
            scope.Event_OFF[eventName] = $rootScope.$on(eventName,callback);
            scope.$on('$destroy',function(){
                // console.log(scope);
                for(var i in scope.Event_OFF ){
                    console.log('destory:'+i);
                    scope.Event_OFF[i]();
                }
            });
        },
        //发布 事件
        $broadcast:function(eventName,data){
            $rootScope.$emit(eventName,data);
        }
    }
}]);